﻿using FI.BatchJob.Web.Data.Entitities;
using FI.BatchJob.Web.Services;
using MimeKit;
using Serilog;
using System;

public class EmailSender : IEmailSender
{
    /// <summary>
    /// Sends the mail.
    /// </summary>
    /// <param name="emailTitle">The email title.</param>
    /// <param name="emailBody">The email body.</param>
    /// <param name="config">The configuration.</param>
    /// <returns></returns>
    public bool SendMail(string emailTitle, string emailBody, MailConfig config)
    {
        try
        {
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress(config.MailFrom, config.MailFrom));
            foreach (var mailTo in config.MailTo.Replace("；", ";").Replace("，", ";").Replace(",", ";").Split(';'))
            {
                message.To.Add(new MailboxAddress(mailTo, mailTo));
            }
            message.Subject = string.Format(emailTitle);
            message.Body = new TextPart("html")
            {
                Text = emailBody
            };
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect(config.MailHost, 25, false);

                client.Authenticate(config.MailUser, config.MailPwd);
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                client.Send(message);
                client.Disconnect(true);
            }
            return true;

        }
        catch (Exception ex)
        {
            Log.Error(ex.ToString());
            return false;
        }
    }
}
